<?php

declare(strict_types=1);

namespace App\Resource\Service;

use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Model\GroundPromotionUserModel;
use EasyWeChat\Factory;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\CoroutineHandler;
use League\Flysystem\Filesystem;

class GroundPromotionUserService extends BaseService
{
    /**
     * @Inject
     * @var GroundPromotionUserModel
     */
    protected $groundModel;
    /**
     * @Inject()
     * @var Filesystem
     */
    protected $filesystem;

    /***
     * @param array $param
     * @param int $perPage
     * @param array|string[] $field
     * @return array
     */
    public function getList(array $param, int $perPage = 100, array $field = ['*'])
    {
        $query = $this->groundModel::query();
        $where['is_deleted'] =0;
        if (isset($param['name']) && !empty($param['name'])) {
            $query->whereRaw('INSTR(name, ?) > 0', [$param['name']]);
        }
        if (isset($param['tel']) && !empty($param['tel'])) {
            $query->whereRaw('INSTR(tel, ?) > 0', [$param['tel']]);
        }
        if (isset($param['create_at']) && !empty($param['create_at'])) {
            $query->where('create_at', '>', $param['create_at']);
        }

        if ((empty($param['status'])&&$param['status']==='0'||$param['status']==1)) {
            $where['status'] = $param['status'];
        }
        $list = $query->where($where)->select($field)->orderBy('create_at', 'desc')->paginate($perPage);
        if ($list) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $list];
        }
        return ['code' => ErrorCode::SERVER_ERROR];
    }


    /**
     * @param array $params
     *
     * @return array
     */
    public function add(array $params, int $uid)
    {
        $params['admin_user_id'] = $uid;
        $res = $this->groundModel::create($params);
        $code_url = $this->getCodeUrl($res->id);
        if($code_url){
            $code_url = implode(',',$code_url);
            $res->update(['code_url'=>$code_url]);
        }
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $res -> id]];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function update(int $id,array $params)
    {
        $res = $this->groundModel::where(['id' => $id])->update($params);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $id]];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param int $id
     *
     * @return array
     */
    public function delete(int $id)
    {

        $res = $this->groundModel::where('id', $id)->update([
            'is_deleted' => 1
        ]);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $id]];
        }


        return ['code' => ErrorCode::NOT_IN_FORCE];
    }


    public function getCodeUrl(int $id)
    {
        $options = [
            'app_id' => config('wechat.app_id'),
            'secret' => config('wechat.secret'),
            'guzzle' => [ // 配置
                'verify' => false,
                'timeout' => 4.0,
            ],
        ];
        $app = Factory::miniProgram($options);
        $handler =new CoroutineHandler();
        // 设置 HttpClient，部分接口直接使用了 http_client。
        $config = $app['config']->get('http', []);
        $config['handler'] = $stack = HandlerStack::create($handler);
        $app->rebind('http_client', new Client($config));
        // 部分接口在请求数据时，会根据 guzzle_handler 重置 Handler
        $app['guzzle_handler'] = $handler;
        $response300  = $app->app_code->get('pages/authorizedLogin/authorizedLogin?ground_promotion_user_id='.$id,  ['width'=>300]);
        $response600 = $app->app_code->get('pages/authorizedLogin/authorizedLogin?ground_promotion_user_id='.$id, ['width'=>600]);
        $response1280= $app->app_code->get('pages/authorizedLogin/authorizedLogin?ground_promotion_user_id='.$id, ['width'=>1280]);
        $date =date("YmdHis");
        $time = time();
        $FileName300 = $date  . $time .$id.'_300'. ".png";
        $FileName600 = $date  . $time .$id.'_600'. ".png";
        $FileName1280 = $date  . $time .$id.'_1280'. ".png";
        $this->filesystem->write(env('OSS_DIR')  .'/mini/'. $FileName300, $response300->getBody()->getContents());
        $this->filesystem->write(env('OSS_DIR')  .'/mini/'. $FileName600, $response600->getBody()->getContents());
        $this->filesystem->write(env('OSS_DIR')  .'/mini/'. $FileName1280, $response1280->getBody()->getContents());
        $codeUrl = [
            'https://' . env('OSS_BUCKET') . '.' . env('OSS_ENDPOINT') . '/' . env('OSS_DIR') . '/mini/' . $FileName300,
            'https://' . env('OSS_BUCKET') . '.' . env('OSS_ENDPOINT') . '/' . env('OSS_DIR') . '/mini/' . $FileName600,
            'https://' . env('OSS_BUCKET') . '.' . env('OSS_ENDPOINT') . '/' . env('OSS_DIR') . '/mini/' . $FileName1280,
        ];
        return $codeUrl;
    }
//    public function getCodeUrl(int $id)
//    {
//        $options = [
//            'app_id' => config('wechat.app_id'),
//            'secret' => config('wechat.secret'),
//            'guzzle' => [ // 配置
//                'verify' => false,
//                'timeout' => 4.0,
//            ],
//        ];
//        $page = 'pages/authorizedLogin/authorizedLogin';
//        $response300 = $this->miniAppService->getMiniAppCodeUrl($this->miniAppService::CODE_URL_NO_LIMIT, [
//            "scene" => $id,
//            'page' => $page,
//            "width" => 300,
//            'is_hyaline' => true,
//        ]);
//        $response600 = $this->miniAppService->getMiniAppCodeUrl($this->miniAppService::CODE_URL_NO_LIMIT, [
//            "scene" => $id,
//            'page' => $page,
//            "width" => 600,
//            'is_hyaline' => true,
//        ]);
//        $response1280 = $this->miniAppService->getMiniAppCodeUrl($this->miniAppService::CODE_URL_NO_LIMIT, [
//            "scene" => $id,
//            'page' => $page,
//            "width" => 1280,
//            'is_hyaline' => true,
//        ]);
//        $codeUrl = [
//            $response300,$response600,$response1280
//        ];
//        return $codeUrl;
//    }
}
